const path = require('path');

const dotenvFile = path.join(__dirname,'.env');

require('dotenv').config({
  path:dotenvFile
})
console.log(process.env.HOST); //localhost
console.log(process.env.PORT); //27017
console.log(process.env.DB); //test

console.log(process.env.URL); //mongodb://${HOST}/${DB}
//↑ 并不支持解析 ${}
//So 可以使用 dotenv-expand ↓
require('dotenv-expand')(
  require('dotenv').config({
    path:dotenvFile
  })
)
console.log(process.env.URL); //mongodb://localhost/test

//https://francoisbest.com/posts/2023/dotenv-is-dead?ref=dailydev
//Dotenv is dead
/*
Today I learned from Liran Tal that Node.js 20.6.0 brings support for loading environment variable files, just like the popular dotenv package does:

node --env-file=.env main.mjs
You can even load multiple files:

node --env-file=.env --env-file=.env.local main.mjs


> Note
>
> It does not seem to support unescaped multi-line values though, which dotenv v15 supports.

This post could have ended here, but I’ll take this opportunity to pass the overtly click-baity title and talk about how I manage environment variables in my Node.js projects.

There are several issues with reading directly from process.env:

It’s not type safe
It’s not validated
It’s not immutable
*/
